package com.tzinfo.tzt.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MKMapViewListener;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.PopupClickListener;
import com.baidu.mapapi.map.PopupOverlay;
import com.baidu.mapapi.map.RouteOverlay;
import com.baidu.mapapi.map.TransitOverlay;
import com.baidu.mapapi.search.MKAddrInfo;
import com.baidu.mapapi.search.MKBusLineResult;
import com.baidu.mapapi.search.MKDrivingRouteResult;
import com.baidu.mapapi.search.MKPlanNode;
import com.baidu.mapapi.search.MKPoiResult;
import com.baidu.mapapi.search.MKSearch;
import com.baidu.mapapi.search.MKSearchListener;
import com.baidu.mapapi.search.MKShareUrlResult;
import com.baidu.mapapi.search.MKSuggestionResult;
import com.baidu.mapapi.search.MKTransitRouteResult;
import com.baidu.mapapi.search.MKWalkingRouteResult;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.tzinfo.tzt.R;
import com.tzinfo.tzt.activity.util.MyApplication;
import com.tzinfo.tzt.config.FilterConfig;
import com.tzinfo.tzt.domain.LocationGeocoder;

public class MapRoutePlanActivity extends BaseActivity implements
		OnClickListener {

	// 百度地图相关
	private MapView mMapView = null; // 地图View
	private MapController mMapController = null;
	private GeoPoint myLoctaionGP = null;
	private GeoPoint locationPoint = null;
	private MKMapViewListener mMapListener = null;
	private BMapManager mBMapManager = null;
	private MKSearch mSearch = null; // 搜索模块，也可去掉地图模块独立使用
	// 定位相关
	private LocationClient mLocClient = null;
	private MyLocationListenner myListener = new MyLocationListenner();
	private LocationData locData = null;
	private MyLocationOverlay myLocationOverlay = null;
	private boolean isRequestLocation = false;
	private LocationGeocoder geocoder;

	// 变量
	public static double locationLon = 0;
	public static double locationLat = 0;
	public static String houseName = "";
	private int tabBtn = 0;
	public static MapRoutePlanActivity activity;

	// UI组件
	private RadioButton mBtnDrive = null; // 驾车搜索
	private RadioButton mBtnTransit = null; // 公交搜索
	private RadioButton mBtnWalk = null; // 步行搜索
	private Button backBtn = null;

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			// 设置路线
			SearchButtonProcess();
		};
	};

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		activity=this;

		if (mBMapManager == null) {
			mBMapManager = new BMapManager(getApplicationContext());
			mBMapManager.init(MyApplication.strKey,
					new MyApplication.MyGeneralListener());
		}
		setContentView(R.layout.activity_routeplan);
		initMapView();
		// 初始化搜索模块，注册事件监听
		mSearch = new MKSearch();
		mSearch.init(mBMapManager, new MKSearchListener() {

			@Override
			public void onGetPoiDetailSearchResult(int type, int error) {
			}

			public void onGetDrivingRouteResult(MKDrivingRouteResult res,
					int error) {
				// 错误号可参考MKEvent中的定义
				if (error != 0 || res == null) {
					Toast.makeText(MapRoutePlanActivity.this, "抱歉，未找到结果",
							Toast.LENGTH_SHORT).show();
					return;
				}
				RouteOverlay routeOverlay = new RouteOverlay(
						MapRoutePlanActivity.this, mMapView);
				// 此处仅展示一个方案作为示例
				routeOverlay.setData(res.getPlan(0).getRoute(0));
				mMapView.getOverlays().clear();
				mMapView.getOverlays().add(routeOverlay);
				mMapView.refresh();
				// 使用zoomToSpan()绽放地图，使路线能完全显示在地图上
				mMapView.getController().zoomToSpan(
						routeOverlay.getLatSpanE6(),
						routeOverlay.getLonSpanE6());
				mMapView.getController().animateTo(res.getStart().pt);
			}

			public void onGetTransitRouteResult(MKTransitRouteResult res,
					int error) {
				if (error != 0 || res == null) {
					Toast.makeText(MapRoutePlanActivity.this, "抱歉，未找到结果",
							Toast.LENGTH_SHORT).show();
					return;
				}
				TransitOverlay routeOverlay = new TransitOverlay(
						MapRoutePlanActivity.this, mMapView);
				// 此处仅展示一个方案作为示例
				routeOverlay.setData(res.getPlan(0));
				mMapView.getOverlays().clear();
				mMapView.getOverlays().add(routeOverlay);
				mMapView.refresh();
				// 使用zoomToSpan()绽放地图，使路线能完全显示在地图上
				mMapView.getController().zoomToSpan(
						routeOverlay.getLatSpanE6(),
						routeOverlay.getLonSpanE6());
				mMapView.getController().animateTo(res.getStart().pt);
			}

			public void onGetWalkingRouteResult(MKWalkingRouteResult res,
					int error) {
				if (error != 0 || res == null) {
					Toast.makeText(MapRoutePlanActivity.this, "抱歉，未找到结果",
							Toast.LENGTH_SHORT).show();
					return;
				}
				RouteOverlay routeOverlay = new RouteOverlay(
						MapRoutePlanActivity.this, mMapView);
				// 此处仅展示一个方案作为示例
				routeOverlay.setData(res.getPlan(0).getRoute(0));
				mMapView.getOverlays().clear();
				mMapView.getOverlays().add(routeOverlay);
				mMapView.refresh();
				// 使用zoomToSpan()绽放地图，使路线能完全显示在地图上
				mMapView.getController().zoomToSpan(
						routeOverlay.getLatSpanE6(),
						routeOverlay.getLonSpanE6());
				mMapView.getController().animateTo(res.getStart().pt);

			}

			public void onGetAddrResult(MKAddrInfo res, int error) {
			}

			public void onGetPoiResult(MKPoiResult res, int arg1, int arg2) {
			}

			public void onGetBusDetailResult(MKBusLineResult result, int iError) {
			}

			@Override
			public void onGetSuggestionResult(MKSuggestionResult res, int arg1) {
			}

			@Override
			public void onGetShareUrlResult(MKShareUrlResult mkshareurlresult,
					int i, int j) {
				// TODO Auto-generated method stub

			}

		});

		// 设定搜索按钮的响应
		mBtnDrive = (RadioButton) this.findViewById(R.id.radio_top_btn1);
		mBtnTransit = (RadioButton) this.findViewById(R.id.radio_top_btn2);
		mBtnWalk = (RadioButton) this.findViewById(R.id.radio_top_btn3);

		mBtnDrive.setOnClickListener(this);
		mBtnTransit.setOnClickListener(this);
		mBtnWalk.setOnClickListener(this);
		// 设置房源点
		setHousePoint();
	}

	@Override
	protected void onDestroy() {
		mMapView.destroy();
		if (mBMapManager != null) {
			mBMapManager.destroy();
			mBMapManager = null;
		}
		super.onDestroy();
	}

	void SearchButtonProcess() {
		mMapView.getOverlays().clear();
		// 对起点终点的name进行赋值，也可以直接对坐标赋值，赋值坐标则将根据坐标进行搜索
		MKPlanNode stNode = new MKPlanNode();
		if (myLoctaionGP != null) {
			stNode.pt = myLoctaionGP;
			MKPlanNode enNode = new MKPlanNode();
			enNode.pt = new GeoPoint((int) (locationLat * 1E6),
					(int) (locationLon * 1E6));
			// 实际使用中请对起点终点城市进行正确的设定
			if (tabBtn == 1) {
				Toast.makeText(this, "正在加载驾车路线",  Toast.LENGTH_SHORT).show();
				mSearch.drivingSearch("我", stNode, houseName, enNode);
			} else if (tabBtn == 2) {
				Toast.makeText(this, "正在加载公交路线",  Toast.LENGTH_SHORT).show();
				mSearch.transitSearch("我", stNode, enNode);
			} else if (tabBtn == 3) {
				Toast.makeText(this, "正在加载步行路线", Toast.LENGTH_SHORT).show();
				mSearch.walkingSearch("我", stNode, houseName, enNode);
			}
		} else {
			Toast.makeText(this, "抱歉，定位失败",  Toast.LENGTH_SHORT).show();
		}

	}

	@Override
	protected void onPause() {
		mMapView.onPause();
		super.onPause();
	}

	@Override
	protected void onResume() {
		setHousePoint();
		locationPoint = new GeoPoint((int) (locationLat * 1E6),
				(int) (locationLon * 1E6));


		mMapController.setCenter(locationPoint); // 设置地图中心点 不设置默认为天安门
		mMapView.refresh();
		mMapView.refresh();
		mMapView.onResume();
		super.onResume();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mMapView.onSaveInstanceState(outState);

	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		mMapView.onRestoreInstanceState(savedInstanceState);
	}

	private void initMapView() {
		backBtn = (Button) this.findViewById(R.id.bt_back);
		backBtn.setOnClickListener(this);

		mMapView = (MapView) findViewById(R.id.bmapView);// 得到地图视图控件
		mMapController = mMapView.getController();// 初始化控制类
		mMapView.setLongClickable(true);

		mLocClient = new LocationClient(this);
		mLocClient.registerLocationListener(myListener);

		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);// 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setScanSpan(5000);
		mLocClient.setLocOption(option);
		mLocClient.start();

		// mMapController.setMapClickEnable(true);
		// mMapView.setSatellite(false);
		// 初始化地图显示事件监听器，该接口监听地图显示事件，用户需要实现该接口以处理相应事件。
		mMapListener = new MKMapViewListener() {

			@Override
			public void onMapMoveFinish() {
				// 在此处理地图移动完成消息回调
				Log.e("yxw", "onMapMoveFinish：" + mMapView.getZoomLevel() + "");
			}

			@Override
			public void onMapAnimationFinish() {
				// 在此处理地图动画完成回调
				Log.e("yxw", "onMapAnimationFinish：" + mMapView.getZoomLevel()
						+ "");
			}

			@Override
			public void onClickMapPoi(MapPoi mapPoiInfo) {
				// 点击到地图可点标注时会回调此接口
				String title = "";
				if (mapPoiInfo != null) {
					title = mapPoiInfo.strText;
					Toast.makeText(MapRoutePlanActivity.this, title,
							Toast.LENGTH_SHORT).show();
					mMapController.animateTo(mapPoiInfo.geoPt);
				}
			}

			@Override
			public void onGetCurrentMap(Bitmap b) {

				// 截图成功后会回调此接口，回调图片数据，保存在"/mnt/sdcard/test"目录下
				Log.d("test", "test" + "onGetCurrentMap");
				File file = new File("/mnt/sdcard/test.png");
				FileOutputStream out;
				try {
					out = new FileOutputStream(file);
					if (b.compress(Bitmap.CompressFormat.PNG, 70, out)) {
						out.flush();
						out.close();
					}
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onMapLoadFinish() {
				// TODO Auto-generated method stub

			}
		};

		mMapController.enableClick(true);
		mMapController.setZoom(12);// 设置缩放比例
		// 用给定的经纬度构造一个GeoPoint，单位是微度 (度 * 1E6)

		setCenter(MyApplication.locationCode);
		mMapView.setBuiltInZoomControls(true);// 设置内置缩放按钮
		// mMapView.displayZoomControls(true);// 设置缩放按钮可见
		// mMapView.setTraffic(true);//设置是否打开路况图
		// mMapView.setSatellite(true);//设置是否打开卫星图
		mMapView.setDoubleClickZooming(true);// 允许双击改变缩放比例
		mMapView.setOnTouchListener(null);// 设置触摸监听事件

		// 用户注册地图监听器
		mMapView.regMapViewListener(mBMapManager, mMapListener);
		myLocationOverlay = new MyLocationOverlay(mMapView);
		locData = new LocationData();
		myLocationOverlay.setData(locData);
		mMapView.getOverlays().add(myLocationOverlay);
		myLocationOverlay.enableCompass();
		mMapView.refresh();
	}

	private void setHousePoint() {
		// pop demo
		// 创建pop对象，注册点击事件监听接口
		PopupOverlay pop = new PopupOverlay(mMapView, new PopupClickListener() {
			@Override
			public void onClickedPopup(int index) {
				// 在此处理pop点击事件，index为点击区域索引,点击区域最多可有三个
			}
		});
		/**
		 * 准备pop弹窗资源，根据实际情况更改 弹出包含三张图片的窗口，可以传入三张图片、两张图片、一张图片。
		 * 弹出的窗口，会根据图片的传入顺序，组合成一张图片显示. 点击到不同的图片上时，回调函数会返回当前点击到的图片索引index
		 */
		Bitmap[] bmps = new Bitmap[1];
		try {
			bmps[0] = BitmapFactory.decodeStream(getResources()
					.openRawResource(R.drawable.marker));
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 弹窗弹出位置
		GeoPoint ptTAM = new GeoPoint((int) (locationLat * 1E6),
				(int) (locationLon * 1E6));
		// 弹出pop,隐藏pop
		pop.showPopup(bmps, ptTAM, 32);
		// 隐藏弹窗
		// pop.hidePop();

	}

	public void testUpdateClick(int tab) {
		mMapView.getOverlays().clear();
		this.tabBtn = tab;
		isRequestLocation = true;
		mLocClient.requestLocation();
	}

	/**
	 * 监听函数，有新位置的时候，格式化成字符串，输出到屏幕中
	 */
	public class MyLocationListenner implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null)
				return;
			if (MyApplication.location == null) {
				MyApplication.location = new Location("gps");
				MyApplication.location.setLatitude(location.getLatitude());
				MyApplication.location.setLongitude(location.getLongitude());
			}

			if (isRequestLocation) {
				locData.latitude = location.getLatitude();
				locData.longitude = location.getLongitude();
				locData.accuracy = location.getRadius();
				locData.direction = location.getDerect();
				myLocationOverlay.setData(locData);
				mMapView.refresh();
				myLoctaionGP = new GeoPoint((int) (locData.latitude * 1e6),
						(int) (locData.longitude * 1e6));
				mMapController.animateTo(myLoctaionGP,
						mHandler.obtainMessage(1));
				isRequestLocation = false;
			}

		}

		public void onReceivePoi(BDLocation poiLocation) {
			if (poiLocation == null) {
				return;
			}
		}
	}

	private void setCenter(int locationCode) {
		int lat = 0, lng = 0;
		if (locationCode == -1) {
			if (MyApplication.location == null) {
				lng = (int) (FilterConfig.ZUO_BIAO[0][0] * 1E6);
				lat = (int) (FilterConfig.ZUO_BIAO[0][1] * 1E6);
			} else {
				lat = (int) (MyApplication.location.getLatitude() * 1E6);
				lng = (int) (MyApplication.location.getLongitude() * 1E6);
			}

		} else if (locationCode == 0) {
			lng = (int) (FilterConfig.ZUO_BIAO[0][0] * 1E6);
			lat = (int) (FilterConfig.ZUO_BIAO[0][1] * 1E6);
		} else {
			lng = (int) (FilterConfig.ZUO_BIAO[locationCode - 1][0] * 1E6);
			lat = (int) (FilterConfig.ZUO_BIAO[locationCode - 1][1] * 1E6);
		}
		locationPoint = new GeoPoint(lat, lng);
		mMapController.setCenter(locationPoint); // 设置地图中心点 不设置默认为天安门
		mMapView.refresh();
	}

	@Override
	public void onBackPressed() {
		this.finishMap();
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode==KeyEvent.KEYCODE_BACK){
			this.finishMap();
			return false;
		}else{
			return super.onKeyDown(keyCode, event);
		}
	}

	private void finishMap() {
		// mMapView.getOverlays().clear();
		// mMapView.refresh();
		this.goback();
	}

	public void goback() {
		Intent intent = null;
		intent = new Intent(this, MainActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
		startActivity(intent);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bt_back:
			this.finishMap();
			break;
		case R.id.radio_top_btn1:
			testUpdateClick(1);
			break;
		case R.id.radio_top_btn2:
			testUpdateClick(2);
			break;
		case R.id.radio_top_btn3:
			testUpdateClick(3);
			break;

		default:
			break;
		}
	}

}
